import { Component, OnInit, HostBinding, ElementRef } from '@angular/core';
import { ActivatedRoute } from '@angular/router';

import { DocToc, ViewerBaseComponent } from '../../shared';

@Component({
  selector: 'fui-guides-viewer',
  templateUrl: './guides-viewer.component.html',
  styleUrls: ['./guides-viewer.component.sass'],
})
export class GuidesViewerComponent extends ViewerBaseComponent implements OnInit {
  @HostBinding('class') hostClass = 'fui-layout2-content';

  example: string;

  tocs: DocToc[] = [];

  constructor(
    public elem: ElementRef,
    protected route: ActivatedRoute,
  ) {
    super(route);
  }

  ngOnInit() {
    this.route.params.subscribe((params) => {
      this.example = params['path'];
    });
  }

  collectToc() {
    this.tocs = [];

    const headingElements = this.elem.nativeElement.querySelectorAll(`h1, h2`);
    Array.from(headingElements).forEach((element: Element) => {
      const headingId = element.getAttribute('id');
      this.tocs.push(new DocToc(decodeURIComponent(headingId), headingId));
    });
  }

  onContentLoaded() {
    this.collectToc();
    this.scrollToView();
  }
}
